package com.fh.shop.api.pay.biz;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fh.shop.api.common.Constant;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.config.AlipayConfig;
import com.fh.shop.api.exception.PayException;
import com.fh.shop.api.mq.producer.PayProducer;
import com.fh.shop.mapper.IOrderMapper;
import com.fh.shop.Order;
import com.fh.shop.mapper.IMemberMapper;
import com.fh.shop.mapper.IOrderDetailMapper;
import com.fh.shop.mapper.IProductMapper;
import com.fh.shop.message.PayMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service("payService")
@Transactional(rollbackFor = Exception.class)
public class IPayServiceImpl implements IPayService {
    @Resource
    private IOrderMapper orderMapper;
    @Resource
    private IMemberMapper memberMapper;
    @Resource
    private IOrderDetailMapper orderDetailMapper;
    @Resource
    private IProductMapper productMapper;
    @Value("${pay.subject}")
    private String subject;
    @Autowired
    private PayProducer payProducer;

    @Override
    public String orderPay(String orderId) {
        //非空验证
        if (orderId == null){
            throw new PayException(ResponseEnum.PAY_ORDER_ID_IS_NULL);
        }
        //订单验证
        Order order = orderMapper.selectById(orderId);
        if (order == null){
            throw new PayException(ResponseEnum.EDIT_PWD_IS_NULL);
        }

        //根据订单状态判断是否重复支付
        Integer orderStatus = order.getOrderStatus();
        if (orderStatus > Constant.OrderStatus.WAIT_PAY){
            throw new PayException(ResponseEnum.PAY_ORDER_IS_PAY);
        }

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",orderId);
        map.put("total_amount",order.getTotalPrice().toString());
        map.put("subject",subject);
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        String orderJson = JSON.toJSONString(map);

        alipayRequest.setBizContent(orderJson);

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public String aliNotifyUrl(Map<String, String[]> requestParams) {
        try {
            Map<String,String> params = new HashMap<String,String>();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
//                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

            /* 实际验证过程建议商户务必添加以下校验：
                1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
                2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
                3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
                4、验证app_id是否为该商户本身。
            */
            //验签
            if (signVerified){

                //验证交易状态
                String trade_status = params.get("trade_status");
                if (!trade_status.equals("TRADE_SUCCESS")){
                    return "fail";
                }

                //验证订单号
                String out_trade_no = params.get("out_trade_no");
                Order order = orderMapper.selectById(out_trade_no);
                if (order == null){
                    return "fail";
                }

                //根据订单状态判断是否重复支付
                Integer orderStatus = order.getOrderStatus();
                if (orderStatus > Constant.OrderStatus.WAIT_PAY){
                    return "success";
                }

                //验证订单金额
                BigDecimal totalPrice = order.getTotalPrice();
                String total_amount = params.get("total_amount");
                if (!total_amount.equals(totalPrice.toString())){
                    return "fail";
                }

                //验证商家id
                String seller_id = params.get("seller_id");
                if (!seller_id.equals(AlipayConfig.seller_id)){
                    return "fail";
                }

                //验证appid
                String app_id = params.get("app_id");
                if (!app_id.equals(AlipayConfig.app_id)){
                    return "fail";
                }

                //修改数据库支付状态
                Order orderInfo = new Order();
                orderInfo.setId(out_trade_no);
                orderInfo.setOrderStatus(Constant.OrderStatus.PAY_SUCCESS);
                orderMapper.updateById(orderInfo);

                /*//修改会员积分
                Long memberId = order.getMemberId();
                //1积分=1元 积分上取整
                double score = Math.ceil(totalPrice.doubleValue());
                memberMapper.updateScore(memberId,score);

                //增加销量
                QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("orderId",out_trade_no);
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
                orderDetails.forEach(x -> {
                    Long count = x.getCount();
                    Long productId = x.getProductId();
                    productMapper.updateSales(productId,count);
                });*/

                PayMessage payMessage = new PayMessage();
                payMessage.setMemberId(order.getMemberId());
                payMessage.setOrderId(out_trade_no);
                payMessage.setTotalPrice(totalPrice);
                payProducer.payProducer(payMessage);


                return "success";

            }else {//验证失败
               return "fail";
            }

        }  catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
